<template>
  <!--底部导航用户-->
  <div class="user">
    <van-row @click="openModel" style="height:100px;" v-show="!showForm">
      <div v-if="userInfo!=null">
        <van-col span="8">
          <img :src="$baseUrl + userInfo.avatar" style="height:80px;width:80px;margin-top: 10px;" @click="$router.push('/user')"/>
        </van-col>
        <van-col span="14">{{userInfo.username}}</van-col>
      </div>
      <div v-else>
        <van-col span="8">
          <img src="../assets/img/empy/暂无搜索结果.png" style="height:80px;width:80px;"/>
        </van-col>
        <van-col span="14">您还未登录</van-col>
      </div>
      <van-col span="2">
        <van-icon name="arrow" />
      </van-col>
    </van-row>
    <!--登录界面-->
    <div class="login_modal" v-if="showForm">
      <section @click="closeModal">
        <img src="../assets/img/login/请先选择.png" alt="" style="width:100px;height:100px;position: absolute;top:20px;right:20px;">
      </section>
      <van-form @submit="onSubmit" style="border:thin solid lightblue;padding-bottom: 10px;">
        <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
          :rules="[{ required: true, message: '请填写用户名' }]" />
        <van-field v-model="password" type="password" name="密码" label="密码" placeholder="密码"
          :rules="[{ required: true, message: '请填写密码' }]" />
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit">登录</van-button>
        </div>
        <div @click="$router.push('/register')" style="font-size:14px;text-align:center;color: lightgray;">没有账号?前去注册</div>
      </van-form>
      
    </div>
    <van-grid :column-num="3" square>
      <van-grid-item @click="clickItem(item.value)" v-for="(item,index) in gridData" :key="index" :icon="item.icon"
        :text="item.text" />
    </van-grid>
  </div>
</template>

<script>
import { goLogin ,selectUserByToken,selectAllUserIdInCart } from "../request/api";

export default {
  name: "User",
  data() {
    return {
      showForm: false,
      avatar: require('../assets/logo.png'),
      nickName: '点击登录',
      username: '',
      password: '',
      gridData: [
        { value: 0, text: '我的订单', icon: 'orders-o' },
        { value: 1, text: '充值中心', icon: 'cash-on-deliver' },
        { value: 2, text: '礼品卡', icon: 'gift-o' },
        { value: 3, text: '我的收藏', icon: 'goods-collect' },
        { value: 4, text: '我的足迹', icon: 'location-o' },
        { value: 5, text: '会员福利', icon: 'gift-o' },
        { value: 6, text: '地址管理', icon: 'setting' },
        { value: 7, text: '账号安全', icon: 'warn-o' },
        { value: 8, text: '联系客服', icon: 'service-o' },
        { value: 9, text: '帮助中心', icon: 'question-o' },
        { value: 10, text: '注册账号', icon: 'friends' },
        { value: 11, text: '退出登录', icon: 'warning' }
      ],
      userInfo:null
    }
  },
  created() {
    let token = localStorage.getItem('token');
    if (token) {
      if(localStorage.getItem('userInfo')) this.userInfo = JSON.parse(localStorage.getItem('userInfo'))
    }
  },
  methods: {
    //登录
    onSubmit(values) {
      if(this.username == "" || this.password == ""){
        this.$toast.fail('账号密码不能为空！')
        return
      }
      goLogin({
        username: values["用户名"],
        password: values["密码"]
      }).then(res => {
        if (res.code == 666) {
          let token = res.data
          localStorage.setItem('token', token);
          this.$toast.success("不容易呀")
          setTimeout(() => {
            this.closeModal();
          }, 500)
          selectUserByToken(token).then(res=>{
            this.userInfo = res.data
            this.$store.state.userId = res.data.id
            localStorage.setItem('userInfo',JSON.stringify(this.userInfo))
            localStorage.setItem('userId',JSON.stringify(this.$store.state.userId))
            selectAllUserIdInCart().then(res=>{
              let userIdList = res.data
              if(userIdList.length>0){
                this.$store.state.isNewUser = true
                userIdList.forEach(item=>{
                  if(item==this.$store.state.userId) this.$store.state.isNewUser = false
                })
              }
            })
          })
        }
      })

    },
    //点击当前用户名
    openModel() {
      // 判断是否已经登录
      let token = localStorage.getItem('token');
      if (!token) {
        this.showForm = true
      }
      return;
    },
    //关闭模态层和登录窗口
    closeModal() {
      this.showForm = false
      this.username = ""
      this.password = ""
    },
    validator(val) {
      return val.trim().length > 0;
    },
    clickItem(value) {
      if(value==11) {
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        localStorage.setItem('cartList',JSON.stringify([]))
        localStorage.setItem('isNewUser',false)
        this.userInfo = null
        this.username = ''
        this.password = ''
        this.$toast.success('退出登录成功！')
      }else if(value == 10){
        this.$router.push('/register')
      }else if(value == 1){
        this.$router.push('/recharge')
      }else if(value == 3){
        this.$router.push('/collect')
      }else if(value == 6){
        this.$router.push('/address')
      }else if(value == 0){
        this.$router.push('/order')
      }
      else this.$toast.fail('功能暂未开放!');
    }
  }
}
</script>

<style scoped>
  ::v-deep .van-grid ,.van-hairline--top{
    color:#fc4a1a;
  }
.user {
  padding-bottom: .5rem;
}

.van-row {
  height: 100px;
  padding: .2rem 4%;
  font-weight: bold;
  color: white;
  background-color: #fc4a1a;
}

.van-col {
  line-height: 100px;
}

img {
  width: .8rem;
  /*使图片变圆*/
  border-radius: 50%;
  display: block;
}

.login_modal {
  width: 100%;
  /*元素是否有内容都会撑开*/
  height: 100vh;
  position: absolute;
  /* 属性设置元素的堆叠顺序。拥有更高堆叠顺序的元素总是会处于堆叠顺序较低的元素的前面。*/
  /* 结合position使用*/
  z-index: 99;

  /*设置模态层，专门用于取消*/
}
section {
  z-index: 999;
    background: #fff;
    height: 100vh;
    display: flex;
    align-items: center;
  }
.van-form {
    /*绝对定位*/
    position: absolute;
    top: 0;
    left: 0;
    background: #fff;
    margin: 40% 15%;
  }
</style>
